//
//  BrandListViewController.m
//  CarHome
//
//  Created by lanou3g on 15-4-27.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "BrandListViewController.h"
#import "SearchCarRootView.h"
#import "UIImageView+WebCache.h"
#import "Brand.h"
#import "Series.h"
#import "DIsplayCarRootViewController.h"
#import "SeriesInfo.h"
#import "CarListTableViewCell.h"

@interface BrandListViewController () <UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, retain) NSMutableDictionary *allDataDictBrand;
@property (nonatomic, retain) NSMutableArray *allKeysArrayBrand;

@property (nonatomic, retain) NSMutableDictionary *allDataDictCar;
@property (nonatomic, retain) NSMutableArray *allKeysArrayCar;
@property (nonatomic, retain) SearchCarRootView *rootView;
@property (nonatomic, retain) Brand *currentBrand;
@property (nonatomic, retain) NSMutableArray *urls;

@property (nonatomic, assign) BOOL isPush;
@end

@implementation BrandListViewController

- (void)loadView {
    self.allDataDictBrand = [NSMutableDictionary dictionary];
    self.allKeysArrayBrand = [NSMutableArray array];
    self.allDataDictCar = [NSMutableDictionary dictionary];
    self.allKeysArrayCar = [NSMutableArray array];
    self.rootView = [[[SearchCarRootView alloc] initWithFrame:[UIScreen mainScreen].bounds] autorelease];
    self.view = self.rootView;
    [_rootView addMyActivityIndicatorView];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"找车";
    _rootView.brandListTV.dataSource = self;
    _rootView.brandListTV.delegate = self;
    _rootView.carListTV.dataSource = self;
    _rootView.carListTV.delegate = self;
    [_rootView.segmentedControl addTarget:self action:@selector(segmentedControlAction:) forControlEvents:UIControlEventValueChanged];
    [_rootView.carListTV registerNib:[UINib nibWithNibName:@"CarListTableViewCell" bundle:nil] forCellReuseIdentifier:@"findCarIdentifier2"];
    
    [_rootView.brandListTV registerClass:[UITableViewCell class] forCellReuseIdentifier:@"findCarIdentifier1"];
    [self loadData];
}

- (void)segmentedControlAction:(UISegmentedControl *)sender {
    [_allDataDictCar removeAllObjects];
    [_allKeysArrayCar removeAllObjects];
    [HTTPRequest requestWithURL:_urls[_rootView.segmentedControl.selectedSegmentIndex] method:@"GET" result:^(NSData *data) {
        NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        for (NSMutableDictionary *item in dict[@"result"][@"fctlist"]) {
            NSMutableArray *array = [NSMutableArray array];
            for (NSMutableDictionary *subItem in item[@"serieslist"]) {
                Series *series = [[Series new] autorelease];
                [series setValuesForKeysWithDictionary:subItem];
                [array addObject:series];
            }
            [_allDataDictCar setObject:array forKey:item[@"name"]];
        }
        _allKeysArrayCar = [[NSMutableArray alloc] initWithArray:_allDataDictCar.allKeys];
        
        [_rootView.carListTV reloadData];
        
    }];

}

- (void)loadData {
    
    [HTTPRequest requestWithURL:brandListURL method:@"GET" result:^(NSData *data) {
        NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        for (NSDictionary *item in dict[@"result"][@"list"]) {
            Brand *brand = [[Brand new] autorelease];
            [brand setValuesForKeysWithDictionary:item];
            
            if (self.allDataDictBrand[brand.letter] == nil) {
                NSMutableArray *temp = [NSMutableArray array];
                [temp addObject:brand];
                [_allDataDictBrand setObject:temp forKey:brand.letter];
            } else {
                [_allDataDictBrand[brand.letter] addObject:brand];
            }
            
        }
        self.allKeysArrayBrand = [[NSMutableArray alloc] initWithArray:_allDataDictBrand.allKeys];
        
        [_allKeysArrayBrand sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            if ([obj1 compare:obj2] == NSOrderedDescending) {
                return YES;
            }
            return NO;
        }];
        [_rootView removeMyActivityIndicatorViewFromSuperView];
        [_rootView.brandListTV reloadData];
        
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([tableView isEqual:_rootView.brandListTV]) {
        return _allKeysArrayBrand.count;
    } else {
        return _allKeysArrayCar.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([tableView isEqual:_rootView.brandListTV]) {
        return [_allDataDictBrand[_allKeysArrayBrand[section]] count];
    } else {
        return [_allDataDictCar[_allKeysArrayCar[section]] count];
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if ([tableView isEqual:_rootView.brandListTV]) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"findCarIdentifier1" forIndexPath:indexPath];
        Brand *b = _allDataDictBrand[_allKeysArrayBrand[indexPath.section]][indexPath.row];
        cell.textLabel.text = b.brandname;
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:b.brandimg] placeholderImage:[UIImage imageNamed:@"black_default_80*80"]];
        return cell;
    } else {
        CarListTableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:@"findCarIdentifier2" forIndexPath:indexPath];
        Series *s = _allDataDictCar[_allKeysArrayCar[indexPath.section]][indexPath.row];
        [cell2.logo sd_setImageWithURL:[NSURL URLWithString:s.imgurl] placeholderImage:[UIImage imageNamed:@"asd"]];
        cell2.name.text = s.name;
        cell2.fcpprice.text = s.price;
        return cell2;
    }
    
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    
    if ([tableView isEqual:_rootView.brandListTV]) {
        return _allKeysArrayBrand[section];
    } else {
        return _allKeysArrayCar[section];
    }
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if ([tableView isEqual:_rootView.brandListTV]) {
        return _allKeysArrayBrand;
    } else {
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:_rootView.brandListTV]) {
        return 49;
    } else {
        return 90;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([tableView isEqual:_rootView.brandListTV]) {
        
        
        [_allDataDictCar removeAllObjects];
        [_allKeysArrayCar removeAllObjects];
        
        
        self.currentBrand = _allDataDictBrand[_allKeysArrayBrand[indexPath.section]][indexPath.row];
        self.urls = [[NSMutableArray alloc] initWithObjects:carListURLwithBrandID(_currentBrand.ID), carListURLwithBrandID2(_currentBrand.ID), nil];
        _rootView.segmentedControl.selectedSegmentIndex = 0;
        [HTTPRequest requestWithURL:_urls[0] method:@"GET" result:^(NSData *data) {
            NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
            if ([dict[@"result"][@"fctlist"] count] == 0) {
                [_rootView.carListTV reloadData];
            } else {
                for (NSMutableDictionary *item in dict[@"result"][@"fctlist"]) {
                    NSMutableArray *array = [NSMutableArray array];
                    for (NSMutableDictionary *subItem in item[@"serieslist"]) {
                        Series *series = [[Series new] autorelease];
                        [series setValuesForKeysWithDictionary:subItem];
                        [array addObject:series];
                    }
                    [_allDataDictCar setObject:array forKey:item[@"name"]];
                }
                _allKeysArrayCar = [[NSMutableArray alloc] initWithArray:_allDataDictCar.allKeys];
                [_rootView.carListTV reloadData];
            }
        }];
        CGRect rect = _rootView.carView.frame;
        rect.origin.x = kMARGIN_LEFT;
        [UIView animateWithDuration:.4 animations:^{
            _rootView.carView.frame = rect;
            NSLog(@"%f",rect.origin.x);
        }];
        
    } else {
        DIsplayCarRootViewController *displayCarRVC = [[DIsplayCarRootViewController new] autorelease];
        Series *s = _allDataDictCar[_allKeysArrayCar[indexPath.section]][indexPath.row];
        displayCarRVC.seriesID = s.ID;
        displayCarRVC.seriesName = s.name;
        displayCarRVC.hidesBottomBarWhenPushed = YES;
        self.isPush = YES;
        [self.navigationController pushViewController:displayCarRVC animated:YES];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if ([scrollView isEqual:_rootView.brandListTV] && !_isPush) {
        [UIView beginAnimations:nil context:nil];
        
        [UIView setAnimationDuration:.2];
        CGRect rect = _rootView.carView.frame;
        rect.origin.x = CGRectGetMaxX([UIScreen mainScreen].bounds);
        _rootView.carView.frame = rect;
        [UIView commitAnimations];
    }
   
}

- (void)viewDidAppear:(BOOL)animated {

    self.isPush = NO;
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES];
    
}

@end
